#
# Copyright (c) 2024 Black Sesame Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
import subprocess
from string import Template

def backup_android_bp():
    parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    original_file = os.path.join(parent_dir, "Android.bp")
    backup_file = os.path.join(parent_dir, "Android.bp.bk")
    
    if os.path.exists(backup_file) and os.path.exists(original_file):
        os.remove(original_file)
        os.rename(backup_file, original_file)

    try:
        with open(original_file, 'r') as f_in, open(backup_file, 'w') as f_out:
            for line in f_in:
                f_out.write(line)
        print("Backup of Android.bp file successful.")
    except FileNotFoundError:
        print("Original Android.bp file not found.")

def get_pkg_name(path):
    abs_path = os.path.abspath(path)
    if not os.path.exists(abs_path) or not os.path.isdir(abs_path):
        return 1, None

    directory_name = os.path.basename(abs_path)
    return 0, directory_name

def append_android_bp(pkg_name):
    template_file_path = './resource/android_bp/android_bp.template'
    with open(template_file_path, 'r') as template_file:
        template_content = template_file.read()

    template = Template(template_content)
    replaced_content = template.safe_substitute(PKG_NAME=pkg_name)

    target_file_path = '../Android.bp'
    with open(target_file_path, 'a') as target_file:
        target_file.write(replaced_content)
    
    print("new Android.bp is generated. origin file is renamed to 'Android.bp.bk'")
    print("you can run 'mm' to compile to get package[" + pkg_name + "] libraries.")
    print("After compiling please remember to recover origin Android.bp")

def recover_android_bp():
    parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    original_file = os.path.join(parent_dir, "Android.bp")
    backup_file = os.path.join(parent_dir, "Android.bp.bk")
    if os.path.exists(backup_file) and os.path.exists(original_file):
        os.remove(original_file)
        os.rename(backup_file, original_file)

# 1. 备份bp文件 2. 提取pkgname 3. 填充模板 4. 拼接bp 5. mm 6. 删除bp
def android_func(path):
    try:
        backup_android_bp()
    except FileNotFoundError:
        return 1
    
    ret, pkg_name = get_pkg_name(path)
    if ret != 0:
        print("pkg_name [" + pkg_name + "] not exist.")
        return 1
    
    append_android_bp(pkg_name)

    return 0


